package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 *  ID自增工具类
 * @BelongsProject:hm-dianping
 * @BelongsPackage:com.hmdp.utils
 * @Author:zouchangjin
 * @CreateTime:2025-07-08 23:25
 * @Version:1.0
 */
@Component
public class RedisIdWorker {
    /**
     * 初始化时间戳，该时间戳为2022-01-01 00:00:00
     */
    private static final long BEGIN_TIME = 1640995200L;

    private static final int COUNT_BITS = 32;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     *
     * @param keyPrefix 区分业务的前缀
     * @return 最新的唯一的id
     */
    public long nexId(String keyPrefix){
        //1.生成时间戳
        long epochSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long timestamp = epochSecond - BEGIN_TIME;
        //2.生成序列号
        String data = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        long count = stringRedisTemplate.opsForValue().increment("icr" + keyPrefix + ":" + data);
        //3.拼接并返回

        return timestamp << COUNT_BITS | count;
    }
}


